package com.wehealth;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.wehealth.dm.User;
import com.wehealth.util.DataManger;
import com.wehealth.util.GetUrl;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Personal_Info extends Fragment{

	private MainActivity mConext;
	private TextView userAccount;
	private TextView userName;
	private TextView userSex;
	private TextView userAge;
	private TextView userPhoneNum;
	private TextView person_info_address_tv;
	private User user;
	private static  String JSONResult;
	private static final int NET_ERROR = -100;
	private DataManger mdatamanger;
	private ProgressBar mProgress;
	private AlertDialog dialog;
	private TextView account_balanceTv;
	private TextView mCouponTv;
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		mConext =(MainActivity)getActivity();
		
		mProgress =(ProgressBar)mConext.findViewById(R.id.personal_progress);
		
		TextView title=(TextView)mConext.findViewById(R.id.header_title);
		String titlename = mConext.getString(R.string.person_info_title);
		title.setText(titlename);
		int color =mConext.getResources().getColor(R.color.text_color_green);
		title.setTextColor(color);

		 Button bBack = (Button) mConext.findViewById(R.id.header_bBack);
		 bBack.setOnClickListener(new View.OnClickListener()
			{
				public void onClick(View v)
				{		
					mConext.switchContentHome();
				}
			});
		   mdatamanger = mConext.getDataManger();
		   user =mConext.getUserInfo();
			userAccount = (TextView)mConext.findViewById(R.id.person_name);

			userName=(TextView)mConext.findViewById(R.id.person_user_name);


			userSex=(TextView)mConext.findViewById(R.id.person_sex);

			userAge=(TextView)mConext.findViewById(R.id.person_age);
			
			
			userPhoneNum = (TextView)mConext.findViewById(R.id.person_phone_number);
			account_balanceTv = (TextView)mConext.findViewById(R.id.account_balance);;
			mCouponTv =(TextView)mConext.findViewById(R.id.account_coupon);;
			
		
			
			LinearLayout view = (LinearLayout)mConext.findViewById(R.id.modify_info_bt);
			view.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Personal_Info_modify  modify_view = new Personal_Info_modify();
					mConext.switchContent(modify_view);		
				}
			});
			
			person_info_address_tv = (TextView)mConext.findViewById(R.id.person_address);
			String address =user.getaddressr();
			person_info_address_tv.setText(address);
			RegistToConnServer();
			
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 return  inflater.inflate(R.layout.personal_info, null);
	}
	
	
	private void updatePersonInfo(){
        String account = userAccount.getText()+user.getAccount();
        userAccount.setText(account);
        
        if(user.getUserName() !=null){
            String name =userName.getText()+user.getUserName();
            userName.setText(name);
            }
        
        //sex
        String usersex = (String) userSex.getText();
        String sex;
        if(user.getUserSex()==0){
            sex = "男";
            usersex = userSex.getText()+sex;
        }
        if(user.getUserSex()==1){
            sex = "女";
            usersex = userSex.getText()+sex;
        }
        userSex.setText(usersex);
        
        //age
        String age="";
        if(user.getUserAge()!=-1){
         age = String.valueOf(user.getUserAge());
        }
        String userage = userAge.getText()+age;
        userAge.setText(userage);
        
        //phonenumber
        String phonenum;
        if(user.getPhoneNumber() ==null){
            phonenum =" ";
        }else{
            phonenum =user.getPhoneNumber();
        }
       phonenum = userPhoneNum.getText().toString()+phonenum;
        userPhoneNum.setText(phonenum);
        
        String balance = user.getbank()+"元";
        account_balanceTv.setText(balance);
        String coupon = user.getcoupon()+"元";
        mCouponTv.setText(coupon);
        
	}
	
	
	
	private void RegistToConnServer(){
	    mProgress.setVisibility(View.VISIBLE);
	        new Thread(){
	            @Override
	            public void run(){
	                try {
	                    submitData();//initDataFromNet();
	                } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                    e.printStackTrace();
	                    }
	                Message message = new Message();
	                message.what = 0;
	                handler.sendMessage(message);
	            }
	            }.start();
	   }
	
	private void submitData()throws IOException{
	        String httpUrl = GetUrl.GetPersonInfo_Url();
	       HttpPost httpRequest= new HttpPost(httpUrl);
	         List <NameValuePair> params = new ArrayList <NameValuePair>();
	         String userId = String.valueOf(user.getUserId());
	         params.add(new BasicNameValuePair("userID",userId));
	         Log.d("SIMMON"," userId= "+userId);
	         try{
	             httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8) );
	             HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
	             Log.d("SIMMON","   ########4");
	             if(httpResponse.getStatusLine().getStatusCode() == 200)
	             {
	                 Log.d("SIMMON:", "JSONResult="+JSONResult);
	                 JSONResult = EntityUtils.toString(httpResponse.getEntity());
	                 Log.d("SIMMON:", "JSONResult="+JSONResult);
	             }
	         } catch(Exception e){
	             Log.e("SIMMON:",  e.toString());
	         }  
	    }
	    
	

	private Handler handler =new Handler(){
	    @Override
	    public void handleMessage(Message msg){
	        super.handleMessage(msg);
	        mProgress.setVisibility(View.GONE);
	        if(JSONResult!=null){
	            BindNewsData(JSONResult);
	        }else{
	        openDialog(NET_ERROR);
	        }
	    }
	};

	private void BindNewsData(String strJSON){
	    try{
	        Log.d("SIMMON","strJSON="+strJSON);
	            JSONObject jsonObject = new JSONObject(strJSON);
	            JSONArray  aNews =  new JSONArray( jsonObject.getString("result"));
	            String loginName = aNews.getJSONObject(0).getString("loginName");
	            String realName = aNews.getJSONObject(0).getString("realName");
	            String sex = aNews.getJSONObject(0).getString("sex");
	            String age = aNews.getJSONObject(0).getString("age");
	            String phone = aNews.getJSONObject(0).getString("phone");
	            String bank = aNews.getJSONObject(0).getString("bank");
	            String coupon = aNews.getJSONObject(0).getString("coupon");
	            
	            user.setAccount(loginName);
	            user.setUserName(realName);
	            user.setPhoneNumber(phone);
	            int ageInt = Integer.valueOf(age);
	            user.setUserAge(ageInt);
	            int sexInt;
	            if(sex.equals("男")){
	                sexInt =0;
	            }else{
	                sexInt =1;
	                }
	            user.setUserSex(sexInt);
	            user.setbank(bank);
	            user.setcoupon(coupon);
	            updatePersonInfo();
               mdatamanger.delUserDate();
               mdatamanger.storeUserInfo(user);
	    }catch(JSONException ex)
	    {
	            Log.e("JSON Error: ", ex.toString()); 
	    }
	    
	}
	
	
	   private void openDialog(final int result){
	       String login_result = mConext.getString(R.string.regist_fail);
	       switch (result) {
	       case NET_ERROR:
	           login_result = getString(R.string.net_connet_fail);
	           break;
	       default:
	           if(result > 0){
	               login_result = getString(R.string.regist_success);
	               //mDataManger.delUserDate();
	               //user.setUserId(result);
	               //mDataManger.storeUserInfo(user);
	           }else{
	               login_result =getString(R.string.regist_fail);
	           }
	           break;
	   }

           AlertDialog.Builder builder = new AlertDialog.Builder(mConext); 
              View view = LayoutInflater.from(mConext).inflate(R.layout.dialog_self_viewbt,null);
              TextView textview = (TextView)view.findViewById(R.id.dialog_self_tx);
              textview.setText(login_result);
              Button okBt =(Button)view.findViewById(R.id.dialog_self_bt);
              String okBtBtStr ="确定";
              okBt.setText(okBtBtStr);
              okBt.setOnClickListener(new OnClickListener() {
                 
                 @Override
                 public void onClick(View arg0) {
                     // TODO Auto-generated method stub
                     if(result > 0){
                         Home vHome = new Home();
                         mConext.switchContent(vHome);           
                         }
                     dialog.cancel();
                 }
             });
              builder.setView(view);
              dialog=  builder.create();
              dialog.show();
	    }
	    
	
	
	

}
